package com.delu.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.delu.entity.UserMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
@Slf4j
public class MySocketHander implements WebSocketHandler {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 为了保存在线的用户信息,在方法中新建一个list存储一下[实际项目根据复杂度,可以存储到数据库]
     */

    private static final List<WebSocketSession> SESSIONS = Collections.synchronizedList(new ArrayList<>());

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {

        log.info("链接成功....");

        SESSIONS.add(webSocketSession);

        String userName = (String) webSocketSession.getAttributes().get("WEBSOCKET_USERNAME");

        if (userName != null) {

            JSONObject obj = new JSONObject();

            obj.put("count", SESSIONS.size());

            users(obj);

            webSocketSession.sendMessage(new TextMessage(obj.toJSONString()));
        }

    }

    private void users(JSONObject obj) {

        List<String> userNames = new ArrayList<>();
        for (WebSocketSession webSocketSession : SESSIONS) {
            userNames.add((String) webSocketSession.getAttributes().get("WEBSOCKET_USERNAME"));
        }
        obj.put("users", userNames);
    }


    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        log.info("处理要发送的信息");

        JSONObject msg = JSON.parseObject(webSocketMessage.getPayload().toString());

        JSONObject obj = new JSONObject();

        String username = (String) webSocketSession.getAttributes().get("WEBSOCKET_USERNAME");

        String to1 = msg.getString("to");

        String msg1 = msg.getString("msg");

        Integer type = msg.getInteger("type");

        UserMessage userMessage = new UserMessage().setUser(username).setMessage(msg1).setToUser(to1).setType(type);

        mongoTemplate.save(userMessage, "user_message");

        if (msg.getInteger("type") == 1) {

            obj.put("msg", msg.getString("msg"));

            sendMessageToUsers(new TextMessage(obj.toJSONString()));

        }else {

            String to = msg.getString("to");

            System.out.println(msg.getString("msg"));

            obj.put("msg", msg.getString("msg"));

            sendMessageToUser(to, new TextMessage(obj.toJSONString()));
        }
    }

    private void sendMessageToUsers(TextMessage message) {

        log.info("发送消息给所用用户");
        for (WebSocketSession user : SESSIONS) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void sendMessageToUser(String userName, TextMessage message) {

        log.info("发消息给某个用户");
        for (WebSocketSession user : SESSIONS) {
            if (user.getAttributes().get("WEBSOCKET_USERNAME").equals(userName)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }


    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {

        if (webSocketSession.isOpen()) {

            webSocketSession.close();
        }

        log.info("链接时出错,关闭链接.....");

        SESSIONS.remove(webSocketSession);

    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {

        log.info("链接关闭" + closeStatus.toString());

        SESSIONS.remove(webSocketSession);

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
